﻿using BCCommon;
using BCCommon.Enums;
using BCEntity.TMS.HealthReport;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;

namespace BCData.TMS.HealthReport
{
    public class HealthReportData : IHealthReportData
    {
        private readonly IDatabaseContext databaseContext;

        private const string QUERY = @"SELECT HealthReportId,IsFever,IsCoughs,DiscomfortContent,CreateTime,ReportDate,Role,CompanyId,UserName,AdminId,UserId,DriverId,
                                    Temperature,TemperaturePhoto,TotalCholesterol,Triglyceride,HighDensityLipoprotein,LDL,SystolicPressure,DiastolicPressure,BloodGlucose,HeartBeat,Height,Weight 
                                    FROM HealthReport";

        public HealthReportData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        public async Task<HealthReportEntity> CreateAsync(HealthReportEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("HealthReport", new string[] { "IsFever", "IsCoughs", "DiscomfortContent", "ReportDate", "Role","CompanyId", "UserName", "AdminId", "UserId", "DriverId",
                    "Temperature", "TemperaturePhoto", "TotalCholesterol","Triglyceride","HighDensityLipoprotein","LDL", "SystolicPressure", "DiastolicPressure", "BloodGlucose", "HeartBeat", "Height", "Weight" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?IsFever", entity.IsFever, DbType.Boolean);
            parameters.Add("?IsCoughs", entity.IsCoughs, DbType.Boolean);
            parameters.Add("?DiscomfortContent", entity.DiscomfortContent, DbType.AnsiString);
            parameters.Add("?ReportDate", DateTime.Now, DbType.Date);
            parameters.Add("?Role", entity.Role.ToString(), DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int64);
            parameters.Add("?UserName", entity.UserName, DbType.AnsiString);
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64);
            parameters.Add("?UserId", entity.UserId, DbType.Int64);
            parameters.Add("?DriverId", entity.DriverId, DbType.Int64);
            parameters.Add("?Temperature", entity.Temperature, DbType.Decimal);
            parameters.Add("?TemperaturePhoto", entity.TemperaturePhoto, DbType.AnsiString);
            parameters.Add("?TotalCholesterol", entity.TotalCholesterol, DbType.Decimal);
            parameters.Add("?Triglyceride", entity.Triglyceride, DbType.Decimal);
            parameters.Add("?HighDensityLipoprotein", entity.HighDensityLipoprotein, DbType.Decimal);
            parameters.Add("?LDL", entity.LDL, DbType.Decimal);
            parameters.Add("?SystolicPressure", entity.SystolicPressure, DbType.Decimal);
            parameters.Add("?DiastolicPressure", entity.DiastolicPressure, DbType.Decimal);
            parameters.Add("?BloodGlucose", entity.BloodGlucose, DbType.Decimal);
            parameters.Add("?HeartBeat", entity.HeartBeat, DbType.Int32);
            parameters.Add("?Height", entity.Height, DbType.Int32);
            parameters.Add("?Weight", entity.Weight, DbType.Decimal);
            sql = string.Format("{0} {1} WHERE HealthReportId = LAST_INSERT_ID()", sql, QUERY);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<HealthReportEntity>(sql, parameters);
        }

        public async Task<(IEnumerable<HealthReportEntity>, int)> GetListAsync(long? companyId,DateTime? start, DateTime? end, bool? ascending, int? index, int? size, long? userId, RoleType? role, bool? isFever, bool? isCoughs)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (companyId.HasValue)
            {
                wheres.Add("CompanyId = ?CompanyId");
                parameters.Add("?CompanyId", companyId.Value, DbType.Int64);
            }
            if (start.HasValue)
            {
                wheres.Add("DATE(ReportDate) >= DATE(?Start)");
                parameters.Add("?Start", start.Value, DbType.Date);
            }
            if (end.HasValue)
            {
                wheres.Add("DATE(ReportDate) <= DATE(?End)");
                parameters.Add("?End", end.Value, DbType.Date);
            }
            if (role.HasValue)
            {
                wheres.Add("Role=?Role");
                parameters.Add("?Role", role.Value.ToString(), DbType.AnsiString);
                if (userId.HasValue)
                {
                    if (role.Value == RoleType.Admin)
                    {
                        wheres.Add("AdminId=?AdminId");
                        parameters.Add("?AdminId", userId.Value, DbType.Int64);
                    }
                    else if (role.Value == RoleType.Driver)
                    {
                        wheres.Add("UserId=?UserId");
                        parameters.Add("?UserId", userId.Value, DbType.Int64);
                    }
                }
            }
          
            if (isFever.HasValue)
            {
                wheres.Add("IsFever=?IsFever");
                parameters.Add("?IsFever", isFever.Value, DbType.Boolean);
            }
            if (isCoughs.HasValue)
            {
                wheres.Add("IsCoughs=?IsCoughs");
                parameters.Add("?IsCoughs", isCoughs, DbType.Boolean);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime {2} LIMIT {3},{4};SELECT COUNT(1) FROM HealthReport {1}",
                QUERY,
                wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : string.Empty,
                (ascending.HasValue && ascending.Value) ? "ASC" : "DESC",
                (index == 0 ? 0 : index - 1) * size,
                size);
            return await this.databaseContext.Slave.QueryMultipleAsync<HealthReportEntity, int>(sql, parameters);
        }

        public async Task<IEnumerable<HealthReportEntity>> GetListByDays(int? timeSpan)
        {
            string sql = string.Format("{0} WHERE ReportDate >= DATE_ADD(CURDATE(), INTERVAL - {1} DAY)", QUERY, timeSpan);
            return await this.databaseContext.Slave.QueryAsync<HealthReportEntity>(sql);
        }

        public async Task<IEnumerable<HealthReportEntity>> GetAnalysisUserListAsync(int? timeSpan, RoleType role, long userId)
        {
            string sql = string.Format("{0} WHERE {1} = {2} AND Role=?Role", QUERY, (role == RoleType.Driver) ? "DriverId" : "AdminId", userId);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?Role", role.ToString(), DbType.AnsiString);
            return await this.databaseContext.Slave.QueryAsync<HealthReportEntity>(sql, parameters);
        }
    }
}
